package com.itheima;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.itheima.pojo.Emp;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.util.ArrayList;
import java.util.List;

public class WriteExcelDemo1 {
    public static void main(String[] args) {

        WriteCellStyle cellStyle = new WriteCellStyle();
        //表头和内容都是水平居中
        cellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        //设置字体
        WriteFont font = new WriteFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)12);
        cellStyle.setWriteFont(font);

        HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(cellStyle,cellStyle);
		
        //生成Excel
        EasyExcel.write("E:/报表.xlsx", Emp.class)
            	.excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(styleStrategy)
                .registerWriteHandler(new MyColumnStyle())
                .sheet("笑傲江湖")
                .doWrite(genData());
	
    }
    
	//组装数据模型
    private static List<Emp> genData(){
        List<Emp> empList = new ArrayList<Emp>();
        empList.add(new Emp(1, "风清扬", 88, "男", "独孤九剑"));
        empList.add(new Emp(2, "令狐冲", 28, "男", "易筋经"));
        empList.add(new Emp(3, "任盈盈", 25, "女", "魔教圣姑"));
        empList.add(new Emp(4, "任我行", 60, "男", "吸星大法"));
        empList.add(new Emp(5, "东方不败", 48, "男/女", "葵花宝典"));
        return empList;
    }


    static class MyColumnStyle extends AbstractColumnWidthStyleStrategy {

        @Override
        protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList,
                                      org.apache.poi.ss.usermodel.Cell cell,
                                      Head head, Integer relativeRowIndex, Boolean isHead) {
            writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), 4500);
        }
    }
}

